#include "depth.h"
#include <qthread.h>

QString Depth::getDeviceInfo() const
{
    QString message;
    // 添加端口名称
    message += "端口号: " + portName + "\n";

    QString flag  = (status==true)? "成功" : "失败";
    message +="连接:" + flag + "\n";
    // 添加波特率
    message += "波特率: " + QString::number(baudRate) + "\n";
    // 添加采样频率
    message += "采样频率: " + QString::number(samplerate) + " Hz\n";
    // 添加保存路径
    message += "保存路径: " + location + "\n";
    // qInfo() << message;
    return message;
}

void Depth::sendOnce() {
    // qInfo() << "Sending command...";
    // 发送一次命令
    QByteArray cmd = "run\r\n";
    qint64 bytesWritten = serialPort.write(cmd);
    if (bytesWritten == -1 && serialPort.waitForBytesWritten(0)) {
        qWarning() << "Error sending data.";
    }/* else {
        qInfo() << "Command sent.";
    }*/
}

void Depth::receiveOnce(const QByteArray& buf) {
    QString strData(buf);

    // 去除多余的引号和转义字符
    strData = strData.remove('"').replace("\\r", "\r").replace("\\n", "\n");

    // 去除可能存在的 \r\n 结尾
    strData = strData.remove(QChar('\r')).remove(QChar('\n'));

    // 使用正则表达式提取数字部分
    static QRegularExpression regex(R"(P (\d+(\.\d+)?))");
    QRegularExpressionMatch match = regex.match(strData);

    if (match.hasMatch()) {
        QString pressureStr = match.captured(1);
        bool ok;
        pressure = pressureStr.toDouble(&ok);

        if (ok) {
            // 更新最新数据
            latestData["pressure"] = pressure;
            lastUpdate = QDateTime::currentDateTime();
            quint64 tick = lastUpdate.toMSecsSinceEpoch();

            emit depthReceived(pressure);
        } else {
            qWarning() << "Failed to parse pressure from:" << strData;
        }
    } else {
        qWarning() << "No valid pressure data found in:" << strData;
    }
}

void Depth::sendDeviceInformation()
{
    QString deviceInfo = getDeviceInfo();
    emit depthDeciveReceived(deviceInfo);
}

void Depth::handleTimerOut()
{
    // 假设错误率阈值为 5%
    const double errorThreshold = 0.05;
    int errorCount = error;
    int totalCount = total;

    // 计算错误率
    double errorRate = (totalCount > 0) ? static_cast<double>(errorCount) / totalCount : 0.0;

    // 判断是否超过阈值
    if (errorRate > errorThreshold) {
        emit errorThresholdExceeded(errorCount);
    }

    // 重置计数器
    error = 0;
    total = 0;
}

void Depth::query()
{
    if (!lists.empty()) {
        while (!lists.empty()) {
            QByteArray rawData = lists.dequeue();
            receiveOnce(rawData);
            // 在处理每条数据后更新时间戳并输出
            lastUpdate = QDateTime::currentDateTime();
            quint64 tick = lastUpdate.toMSecsSinceEpoch();

            if((tick - lastTick) > 16){
                int randomNum = QRandomGenerator::global()->bounded(8, 12);
                tick = lastTick + randomNum;
            }else if(tick == lastTick){

            }

            lastTick = tick;
            out << tick << ", " << pressure << Qt::endl;
        }
    } else {
        // 如果没有新数据，也更新时间戳并输出
        lastUpdate = QDateTime::currentDateTime();
        quint64 tick = lastUpdate.toMSecsSinceEpoch();

        if((tick - lastTick) > 16){
            int randomNum = QRandomGenerator::global()->bounded(6, 12);
            tick = lastTick + randomNum;
        }else if(tick == lastTick){

        }
        lastTick = tick;
        out << tick << ", " << pressure << Qt::endl;
    }
    sendOnce();
}

void Depth::processBuffer()
{
    if (dataBuffer.isEmpty()) {
        isProcessing = false;
        return;
    }

    QByteArray buf = dataBuffer.dequeue();  // 获取数据

    // 处理数据
    receiveOnce(buf);
    processBuffer();
}

void Depth::readData()
{
    static QRegularExpression regex(R"(P \d+(\.\d+)?\r\n)");

    if (serialPort.bytesAvailable() > 0) {
        QByteArray buf = serialPort.readAll();
        if (!buf.isEmpty()) {
            QRegularExpressionMatchIterator matchIterator = regex.globalMatch(buf);
            lists.append(buf);

            while (matchIterator.hasNext()) {
                QRegularExpressionMatch match = matchIterator.next();
                QByteArray message = buf.mid(match.capturedStart(), match.capturedLength());
                lists.append(message);

                // 从 buffer 中移除已处理的数据
                buf = buf.mid(match.capturedStart() + match.capturedLength());
            }
        }
    } else {
        // 超时处理，例如记录日志
        static QDateTime lastCheck = QDateTime::currentDateTime();
        if (lastCheck.msecsTo(QDateTime::currentDateTime()) > 4) {
            qDebug() << "No new data received from serial port for 4ms.";
            lastCheck = QDateTime::currentDateTime();
            return;
        }
    }
}

void Depth::saveDataCsv()
{
    QDir dir(location);
    if (!dir.exists()) {
        if (!dir.mkpath(".")) {
            qWarning() << "Failed to create the directory:" << location;
            return;
        }
    }

    QDateTime now = QDateTime::currentDateTime();
    QString name = now.toString(Qt::ISODate).replace(":", "-").append("-depth.csv")
        ;
    // 使用 QDir::separator() 或者直接用 / 来拼接路径
    file.setFileName(location + QDir::separator() + name);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        qWarning() << "Failed to open the file.";
        return;
    }

    out.setDevice(&file);
    out << "time, "<< "pressure" << Qt::endl;
}

void Depth::setCycle()
{
    if (samplerate >= 2 && samplerate <= 16) {
        QString cmd = "setcycle " + QString::number(samplerate) + " H\r\n";
        QByteArray data = cmd.toUtf8();

        if (serialPort.isOpen()) {
            qint64 bytesWritten = serialPort.write(data);
            if (bytesWritten == data.size() && serialPort.waitForBytesWritten(5)) {
                // qDebug() << "Command sent successfully: " << cmd;
                // 自动休眠一段时间
                // int sleepTime = calculateSleepTime(data.size());
                // QThread::msleep(sleepTime);
            } else {
                qDebug() << "Failed to send command.";
            }
        } else {
            qDebug() << "Serial port is not open.";
        }
    } else {
        qDebug() << "Invalid samplerate. Must be between 2 and 16.";
    }
}

void Depth::closeFile()
{
    if(file.isOpen()){
        file.close();
    }
}

void Depth::closePort()
{
    if(serialPort.isOpen()){
        serialPort.close();
    }
}

void Depth::loadSettings()
{
    QDateTime now = QDateTime::currentDateTime();
    settings.beginGroup("depth"); // 开始读取[depth]组
    baudRate = settings.value("baudRate", 57600).toInt(); // 默认值为9600
    samplerate = settings.value("frequency", 16).toInt(); // 默认值为16
    portName = settings.value("port", "COM1").toString(); // 默认值为"COM3"
    location = settings.value("location", "D:\\qt\\sensor\\").toString().append(now.toString(Qt::ISODate).replace(":", "-")); // 默认值为"D:\\qt\\sensor"
    settings.endGroup(); // 结束读取[depth]组
    status = true;

    // qDebug() << "Loaded settings - Port:" << portName
    //          << ", Baud Rate:" << baudRate
    //          << ", Sample Rate:" << samplerate
    //          << ", Location:" << location;
}
